package pce

import (
	"fmt"
	"pceservice/internal/pce/strategy"
	"sort"
)

// PathEvaluationResult 路径评估结果
type PathEvaluationResult struct {
	PathID          string  `json:"pathId"`
	TotalDelay      float64 `json:"totalDelay"`      // 总时延(ms)
	TotalHop        int     `json:"totalHop"`        // 总跳数
	TotalCost       uint32  `json:"totalCost"`       // 总成本
	BandwidthUtilization float64 `json:"bandwidthUtilization"` // 带宽利用率
	Score           float64 `json:"score"`           // 综合评分(越高越好)
}

// PathEvaluator 路径评估器
type PathEvaluator struct {
	// 权重配置
	delayWeight      float64
	hopWeight        float64
	costWeight       float64
	bandwidthWeight  float64
}

// NewPathEvaluator 创建路径评估器
func NewPathEvaluator(delayWeight, hopWeight, costWeight, bandwidthWeight float64) *PathEvaluator {
	// 归一化权重
	total := delayWeight + hopWeight + costWeight + bandwidthWeight
	return &PathEvaluator{
	delayWeight:     delayWeight / total,
	hopWeight:       hopWeight / total,
	costWeight:      costWeight / total,
	bandwidthWeight: bandwidthWeight / total,
	}
}

// Evaluate 评估单条路径
func (pe *PathEvaluator) Evaluate(path *strategy.Path) (*PathEvaluationResult, error) {
	if path == nil || len(path.Links) == 0 {
		return nil, fmt.Errorf("无效的路径")
	}

	result := &PathEvaluationResult{
	PathID: path.ID,
	}

	// 计算总时延、总跳数、总成本
	for _, link := range path.Links {
		result.TotalDelay += link.Delay
		result.TotalHop++
		result.TotalCost += link.Metric
		// 简化的带宽利用率计算
		result.BandwidthUtilization += link.Utilization
	}

	// 计算平均带宽利用率
	result.BandwidthUtilization /= float64(len(path.Links))

	// 计算综合评分 (这里使用简单的加权平均，可以根据需求调整算法)
	// 注意：时延和成本越低越好，所以取倒数
	delayScore := 1.0 / (1.0 + result.TotalDelay)
	hopScore := 1.0 / (1.0 + float64(result.TotalHop))
	costScore := 1.0 / (1.0 + float64(result.TotalCost))
	// 带宽利用率越低越好
	bandwidthScore := 1.0 - result.BandwidthUtilization

	result.Score = pe.delayWeight*delayScore + pe.hopWeight*hopScore + pe.costWeight*costScore + pe.bandwidthWeight*bandwidthScore

	return result, nil
}

// EvaluateMultiplePaths 评估多条路径并排序
func (pe *PathEvaluator) EvaluateMultiplePaths(paths []*strategy.Path) ([]*PathEvaluationResult, error) {
	results := make([]*PathEvaluationResult, 0, len(paths))

	for _, path := range paths {
		result, err := pe.Evaluate(path)
		if err != nil {
			return nil, err
		}
		results = append(results, result)
	}

	// 按综合评分降序排序
	sort.Slice(results, func(i, j int) bool {
		return results[i].Score > results[j].Score
	})

	return results, nil
}

// GetBestPath 获取评分最高的路径
func (pe *PathEvaluator) GetBestPath(paths []*strategy.Path) (*strategy.Path, *PathEvaluationResult, error) {
	if len(paths) == 0 {
		return nil, nil, fmt.Errorf("路径列表为空")
	}

	results, err := pe.EvaluateMultiplePaths(paths)
	if err != nil {
		return nil, nil, err
	}

	// 找到对应的路径
	bestResult := results[0]
	for _, path := range paths {
		if path.ID == bestResult.PathID {
			return path, bestResult, nil
		}
	}

	return nil, nil, fmt.Errorf("未找到最佳路径")
}